package fr.lille.inria.adam.lifl.EcoGardeInventory.scrapper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;

import android.util.Log;
import fr.lille.inria.adam.lifl.EcoGardeInventory.Utils.Constantes;

public class RetrieveEntitesTask extends
		HttpAsyncTask<String, Map<String, String>> {
	
	private static final String TAG = "RetrieveEntitesTask";
	
	@Override
	protected Map<String, String> doInBackground(String... params) {
		Log.d(TAG, "start refresh cats");
		Map<String, String> result = new HashMap<String, String>();
		System.out.println("deb retrieve");
		HttpPost allRequest = new HttpPost(Constantes.HTTP_ENTITE); //Je récupère la page de recherche
		List<NameValuePair> pairs = new ArrayList<NameValuePair>();
		pairs.add(new BasicNameValuePair("code_site", params[0]));

		try {
			allRequest.setEntity(new UrlEncodedFormEntity(pairs));
			// Et j'extrais les catgories et leurs identifiants depuis la liste
			// droulante
			HttpResponse response = browser.execute(allRequest);

			String s = getStringContent(response);
			Log.d(TAG, s.substring(12, s.length() - 1));
			JSONArray json = new JSONArray(s.substring(12, s.length() - 1));
			for (int i = 0; i < json.length(); i++) {
				result.put(json.getJSONObject(i).getString("cle"), json
						.getJSONObject(i).getString("libelle"));
			}

			Log.d(TAG,
					String.format("done refresh cats (%d results)",
							result.size()));
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}
}
